package com.example.qsmx;


import com.example.qsmx.Util.MyDBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/user-login")
public class UserLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端用户输入的所有数据
        String userAccount = req.getParameter("userAccount");
        String userPassword = req.getParameter("userPassword");

        // 连接数据库
        Connection connection;
        connection = MyDBUtil.getConnection();

        // 在数据库中查找数据库对应的内容
        String findSql = "SELECT userPassword FROM qsmxusers WHERE userAccount = ?";
        PreparedStatement preparedStatement;
        try {
            preparedStatement = connection.prepareStatement(findSql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //按照 sql 语句查找对应的内容
        try {
            preparedStatement.setString(1, userAccount);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 执行查询并获取结果集
        ResultSet findResultSet;
        try {
            findResultSet = preparedStatement.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 处理结果集
        String password = null;
        try {
            if (findResultSet.next()) {
                password = findResultSet.getString("userPassword");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 如果账号错误，但是密码正确，则返回错误
        if (!userPassword.equals(password)) {
            System.out.println("账号或密码输入错误");
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>" +
                    "alert('账号或密码错误，请重新输入！');" +
                    "window.location.href='login.jsp';</script>')");
            return;
        }

        // 获取或创建session
        HttpSession session = req.getSession(true);

        // 存储数据
        session.setAttribute("userAccount", userAccount);

        // 如果正确，则进入登录后的界面
        System.out.println("登录成功，正在跳转，请稍等");
        req.getRequestDispatcher("WEB-INF/interface.jsp").forward(req, resp);
    }
}
